<template>
	<view>
		<scroll-view class="box" scroll-y="">
			<view class="itembox">
				<view class="leftbox">题目：</view><textarea maxlength="50" v-model="title" auto-height placeholder="限50字" class="rightbox"/>
			</view>
			<view class="itembox">
				<view class="leftbox" style="flex: 1.5;">添加新科目：</view><switch @change="switchChange" class="rightbox"/>
			</view>
			<view class="itembox" v-if="!isaddsubject">
				<view class="leftbox">科目：</view><view @click="choosesubject()" class="rightbox">{{subject}}</view>
			</view>
			<view class="itembox" v-if="isaddsubject">
				<view class="leftbox" style="flex: 1;">新科目：</view><input v-model="newsubject" class="rightbox"/>
			</view>
			<view class="itembox">
				<view class="leftbox">类型：</view><view @click="choosetype()" class="rightbox">{{type}}</view>
			</view>
			<view v-if="type!='填空题'">
				<view class="itembox" v-for="(item, index) in options">
					<view class="leftbox option" :class="{answer: answer.indexOf(String.fromCharCode(65 + index)) !== -1}" style="flex: 0.1;" @click="setanswer(index)">{{String.fromCharCode(65 + index)}}：</view>
					<input v-model="options[index]" class="rightbox" :disabled="type=='判断题'"/>
					<view @click="deloption(index)" class="option" style="background-color: rgba(128, 0, 0, .3);">删除</view>
				</view>
				<button type="primary" size="mini" @click="addoption">添加选项</button>
			</view>
			<view class="itembox">
				<view class="leftbox">答案：</view><input v-model="answer" :disabled="type!='填空题'" class="rightbox" placeholder="非填空题禁止填入"/>
			</view>
			<view class="itembox">
				<view class="leftbox">解析：</view><textarea maxlength="50" v-model="analysis" auto-height placeholder="限50字" class="rightbox"/>
			</view>
		</scroll-view>
		<button type="primary" @click="summit">提交</button>
		
	</view>
</template>

<script>
	import { nextTick } from "vue";
import { getsubjectlist, setquestion } from '../../apis/questionAPI.js'
	export default {
		data() {
			return {
				id: 0,
				title: '',
				subject: '历史',
				newsubject: '',
				type: '单选题',
				options: [],
				answer: '',
				analysis: '',
				isaddsubject: false,
				subjectlist: [],
				oldoptions: []
			};
		},
		onShow() {
			if (this.$store.state.subjectlist.length !== 0) {
				this.subjectlist = this.$store.state.subjectlist
				this.subject = this.$store.state.subjectlist[0]
			} else {
				getsubjectlist().then(res => {
					// console.log(res)
					let arr = []
					for (let i=0; i<res.subjectlist.length; i++) {
						arr.push(res.subjectlist[i].subject)
					}
					// console.log(arr[0])
					this.subjectlist = arr
					this.subject = arr[0]
				})
			}
		},
		onHide() {
			this.title = ''
			this.subject = ''
			this.newsubject = ''
			this.type = '单选题'
			this.options = []
			this.answer = ''
			this.analysis = ''
			this.isaddsubject = false
		},
		computed: {
			typeBack: function() {
				switch (this.type) {
				  case '填空题': return 'tian'
				  case '多选题': return 'duo'
				  case '判断题': return 'pan'
				  case '单选题': return 'dan'
				}
			}
		},
		methods: {
			switchChange(e) {
				this.isaddsubject = e.detail.value
			},
			// 选择科目
			choosesubject() {
				let that = this
				uni.showActionSheet({
					itemList: this.subjectlist,
					success: function (res) {
						that.subject = that.subjectlist[res.tapIndex]
						// console.log(res)
					},
					// fail: function (res) {
					// 	console.log(res.errMsg);
					// }
				})
			},
			// 选择做题类型
			choosetype() {
				let that = this
				let itemList = ['单选题', '多选题', '填空题', '判断题']
				uni.showActionSheet({
					itemList,
					success: function (res) {
						that.answer = ''
						if (itemList[res.tapIndex]=='判断题'){
							if (that.type != '判断题') {
								that.oldoptions = JSON.parse(JSON.stringify(that.options))
							}
							that.options = ['对的', '错的']
							// console.log(that.oldoptions)
						} else if (itemList[res.tapIndex]!='填空题' && that.type == '判断题') {
							// console.log(that.oldoptions)
							that.options = that.oldoptions
						}
						that.type = itemList[res.tapIndex]
						// console.log(res)
					},
					// fail: function (res) {
					// 	console.log(res.errMsg);
					// }
				})
			},
			// 添加选项
			addoption() {
				this.options.push('')
			},
			// 修改答案
			setanswer(index) {
			    const char = String.fromCharCode(65 + index)
			    if (this.type === '多选题') {
			      if (this.answer.indexOf(char) === -1) {
			        const chars = this.answer.split('')
			        let index = 0
			        for (let i = 0; i < chars.length; i++) {
			          // console.log(i, char, chars[i])
			          if (i === 0 && char < chars[i]) {
			            index = 0
			            break
			          } else if (i === chars.length - 1 && char > chars[i]) {
			            index = i + 1
			            break
			          } else if (char < chars[i]) {
			            index = i
			            break
			          }
			        }
			        // console.log(index)
			        chars.splice(index, 0, char)
			        this.answer = chars.join('')
			      } else {
			        this.answer = this.answer.replace(char, '')
			      }
			    } else {
			      this.answer = char
			    }
			},
			  // 删除选项
			deloption (index) {
			    this.options.splice(index, 1)
			    // 修改答案
			    this.answer = this.answer.replace(String.fromCharCode(65 + index), '')
			    const chars = this.answer.split('')
			    console.log(this.answer)
			    for (let i = 0; i < chars.length; i++) {
			      if (chars[i] > String.fromCharCode(65 + index)) {
			        chars[i] = String.fromCharCode(chars[i].charCodeAt() - 1)
			      }
			    }
			    this.answer = chars.join('')
			},
			// 提交问题
			summit () {
				const that = this
				uni.showModal({
					title: '确定提交？',
					confirmColor:'#3A3A3A',
					cancelColor:'#999999',
					confirmText:'确定',
					success: function (res) {
						// console.log(res.content)
						if (res.confirm) {
							if (that.title.split(' ').join('') == '' || (that.isaddsubject && that.newsubject.split(' ').join('') == '') || that.answer.split(' ').join('') == '' || that.analysis.split(' ').join('') == '') {
								uni.showToast({
								    title: '不能有为空的内容',
								    duration: 1000,
								    icon: "none"
								})
								return
							}
							if (that.options.length !== 0) {
								for (let i=0; i<that.options.length; i++) {
									if (that.options[i].split(' ').join('') == '') {
										uni.showToast({
										    title: '选项输入不能为空',
										    duration: 1000,
										    icon: "none"
										})
										return
									}
								}
							}
							if (that.options.length == 0 && that.type != 'tian') {
								uni.showToast({
									title: '未添加选项',
									duration: 1000,
									icon: "none"
								})
								return
							}
							setquestion({
								id: 0,
								title: that.title,
								subject: that.subject,
								newsubject: that.newsubject,
								type: that.typeBack,
								options: that.options,
								answer: that.answer,
								analysis: that.analysis,
								isaddsubject: that.isaddsubject
							}).then(res => {
								that.title = ''
								that.subject = ''
								that.newsubject = ''
								that.type = '单选题'
								that.options = []
								that.answer = ''
								that.analysis = ''
								that.isaddsubject = false
							})
						}
					},
				})
			},
			
		}
	}
</script>

<style lang="less">
	textarea, input {
		border: 1px solid rgba(0,0,0,.2);
		border-radius: 10px;
		width: 100%;
		font-size: 2.5vh;
		padding: 1vh;
	}
	button {
		margin: 2vh;
	}
	.box {
		box-sizing: border-box;
		width: 94vw;
		max-height: 75vh;
		background-color: #f8f8f8;
		margin: 0vh auto;
		margin-top: 2vh;
		padding: 3vw;
		font-size: 2.5vh;
		max-height: 75vh;
		overflow: hidden;
		
		.itembox {
			display: flex;
			justify-content: start;
			margin: 2vh 0;
			align-items: center;
			
			.leftbox {
				flex: 0.7;
			}
			.rightbox {
				flex: 3;
			}
			
			.option {
				box-sizing: border-box;
				border: 1px solid rgba(0,0,0,.2);
				border-radius: 10px;
				padding: 1vh;
				margin: 0 1vh;
			}
			
			.answer {
				background-color: rgba(0, 128, 0, .3);
			}
		}
		.last {
			margin-bottom: 3vw;
		}
	}
	
</style>
